import React, { useEffect, useState } from 'react';
import {
  Box,
  Icon,
  Input,
  MainButton,
  makeToast,
  NumberInput,
  Text,
  ThemeColorType,
} from '@nova-hf/ui';
import { formatPrice } from 'beta/utils/helpers';
import { useTranslation } from 'beta/utils/i18n';
import {
  ContractItemType,
  PaymentCategory,
  useAddExtraPayersMutation,
  useContractQuery,
  useDeleteExtraPayersMutation,
} from 'typings/graphql';

type ChangeCeilingContainerProps = {
  contractId: string;
  color: ThemeColorType;
};

const ChangeCeilingContainer = ({ contractId, color }: ChangeCeilingContainerProps) => {
  const [ceiling, setCeiling] = useState('0');
  const [toLowError, setToLowError] = useState(false);

  const { t } = useTranslation(['stillingar', 'multi']);
  const { data, loading, error, refetch } = useContractQuery({
    variables: {
      input: {
        id: contractId,
      },
    },
    skip: !contractId,
  });

  const contract = data?.contract;
  const extraPayerWithCeiling = contract?.extraPayers?.find(
    (item) => item?.amount && item?.amount > 0 && item?.status === 'Active',
  );
  const currentCeiling = extraPayerWithCeiling?.amount ?? 0;
  const [addCeiling, { loading: addLoading }] = useAddExtraPayersMutation({
    onCompleted: (data) => {
      makeToast.success(t('multi:ceiling.singleSuccess'), '');

      if (data) {
        refetch();
      }
    },
    onError(error) {
      makeToast.danger(t('multi:ceiling.singleFail'), error.message);
    },
  });

  const [deleteCeiling, { loading: deleteLoading }] = useDeleteExtraPayersMutation({
    onCompleted: (data) => {
      makeToast.success(t('multi:ceiling.removeSingleSuccess'), '');

      if (data) {
        refetch();
      }
    },
    onError(error) {
      makeToast.danger(t('multi:ceiling.removeSingleFail'), error.message);
    },
  });

  const extraPayerMap = () => {
    const serviceContractItem = contract?.contractItems?.find(
      (item) => item.type === ContractItemType.Service,
    );

    return {
      contractId: contract?.id,
      amount: parseInt(ceiling, 10),
      customerId:
        serviceContractItem?.__typename === 'ServiceContractItem'
          ? serviceContractItem?.serviceInfo?.userId
          : undefined,
      paymentCategory: PaymentCategory.PaysForExcess,
    };
  };

  const extraPayerInput = extraPayerMap();

  const handleButtonClick = async () => {
    if (ceiling) {
      await addCeiling({
        variables: {
          input: {
            extraPayers: [extraPayerInput],
          },
        },
      });
    }
  };

  const handleDeleteClick = async () => {
    if (ceiling == '0' && extraPayerWithCeiling?.id) {
      await deleteCeiling({
        variables: {
          input: {
            extraPayerIds: [extraPayerWithCeiling?.id],
          },
        },
      });
    }
  };

  useEffect(() => {
    if (ceiling) {
      const numberValue = parseInt(ceiling, 10);
      if (numberValue < 500 && numberValue > 0) setToLowError(true);
      if (numberValue > 499) setToLowError(false);
    }
  }, [ceiling]);

  if (loading) return <Box padding={6}>{t('multi:ceiling.loading')}</Box>;
  if (error || !data?.contract) return <Box padding={6}> {t('multi:ceiling.error')}</Box>;

  return (
    <Box>
      <Box display="flex" flexDirection="column" gap={3}>
        <Text variant="pMediumBold" color="black100">
          {t('multi:ceiling.change')}
        </Text>
        <Text variant="pMediumRegular" color="black100">
          {t('multi:ceiling.description')}
        </Text>
        <Box marginTop={2} display="flex" flexDirection="column" gap={4}>
          <Input
            id="CurrentCeilingInput"
            label={t('multi:ceiling.oldCeiling')}
            value={formatPrice(currentCeiling)}
            name={t('multi:ceiling.currentCeiling')}
            type="text"
            isBold={false}
            disabled={true}
          />
          <NumberInput
            id="CreditCardInput"
            label={t('multi:ceiling.newCeiling')}
            name="New ceiling Input"
            numberType="number"
            value={ceiling}
            required
            disabled={false}
            onChange={(value) => setCeiling(value)}
          />
        </Box>
        {toLowError && (
          <Box
            gap={1}
            display="flex"
            flexDirection="row"
            alignItems="center"
            marginRight="auto"
            width="4/12"
          >
            <Icon icon="info" color="warning" />
            <Text marginRight="auto" color="warning" variant="pSmallRegular">
              {t('multi:ceiling.toLowError')}
            </Text>
          </Box>
        )}
        <Box
          display="flex"
          flexDirection="row-reverse"
          alignItems="center"
          justifyContent="space-between"
          marginTop={10}
        >
          <Box width="4/12">
            <MainButton
              text={t('multi:ceiling.confirm')}
              onClick={handleButtonClick}
              dottedShadow="none"
              colorScheme={color}
              isLoading={loading || addLoading}
              isDisabled={!ceiling || toLowError}
            />
          </Box>
          <Box width="4/12">
            <MainButton
              text={t('multi:ceiling.removeCeiling')}
              onClick={handleDeleteClick}
              dottedShadow="none"
              colorScheme="warning"
              isLoading={loading || deleteLoading}
              isDisabled={!extraPayerWithCeiling}
            />
          </Box>
        </Box>
      </Box>
    </Box>
  );
};

export default ChangeCeilingContainer;
